package com.example.myapplication;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

public class DBHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "campus_trading.db";
    private static final int DATABASE_VERSION = 1;


    private static final String TABLE_RANKING_LIST = "RankingList";
    private static final String COLUMN_ID = "Id";
    private static final String COLUMN_NAME = "Name";
    private static final String COLUMN_IMAGE = "Image"; // 新增字段，存储图片路径



    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }


    // 获取榜单数据，返回自定义对象列表
    public List<RankingItem> getAllRankings() {
        List<RankingItem> rankingList = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_RANKING_LIST, new String[]{COLUMN_NAME, COLUMN_IMAGE},
                null, null, null, null, null);

        if (cursor.moveToFirst()) {
            do {
                String name = cursor.getString(0);
                String imagePath = cursor.getString(1);
                rankingList.add(new RankingItem(name, imagePath));
            } while (cursor.moveToNext());
        }
        cursor.close();
        return rankingList;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE users (user_id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, password TEXT NOT NULL);");
        db.execSQL("CREATE TABLE products (product_id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, name TEXT NOT NULL, description TEXT, price REAL NOT NULL, image_path TEXT, FOREIGN KEY(user_id) REFERENCES users(user_id));");
        db.execSQL("CREATE TABLE transactions (transaction_id INTEGER PRIMARY KEY AUTOINCREMENT, buyer_id INTEGER, seller_id INTEGER, product_id INTEGER, status TEXT, date TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY(buyer_id) REFERENCES users(user_id), FOREIGN KEY(seller_id) REFERENCES users(user_id), FOREIGN KEY(product_id) REFERENCES products(product_id));");
        db.execSQL("CREATE TABLE reviews (review_id INTEGER PRIMARY KEY AUTOINCREMENT, transaction_id INTEGER, rating INTEGER, comment TEXT, FOREIGN KEY(transaction_id) REFERENCES transactions(transaction_id));");

        // 创建榜单表，新增图片路径字段
        String CREATE_RANKING_TABLE = "CREATE TABLE " + TABLE_RANKING_LIST + " ("
                + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + COLUMN_NAME + " TEXT UNIQUE, "
                + COLUMN_IMAGE + " TEXT)";
        db.execSQL(CREATE_RANKING_TABLE);


        // 使用传递的 `db` 对象插入模拟数据
        insertMockData(db);

        insertInitialRankingData(db);

    }

    private void insertInitialRankingData(SQLiteDatabase db) {
        insertRanking(db, "电子产品榜", "drawable/laptop");
        insertRanking(db, "服装鞋包榜", "drawable/backpack");
    }

    public void insertRanking(SQLiteDatabase db, String name, String imagePath) {
        ContentValues values = new ContentValues();
        values.put(COLUMN_NAME, name);
        values.put(COLUMN_IMAGE, imagePath);
        db.insertWithOnConflict(TABLE_RANKING_LIST, null, values, SQLiteDatabase.CONFLICT_IGNORE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS users");
        db.execSQL("DROP TABLE IF EXISTS products");
        db.execSQL("DROP TABLE IF EXISTS transactions");
        db.execSQL("DROP TABLE IF EXISTS reviews");
        onCreate(db);
    }

    // 模拟数据插入方法

    private void insertMockData(SQLiteDatabase db) {
        // 插入用户数据
        db.execSQL("INSERT INTO users (username, password) VALUES " +
                "('张三', '123456'), " +
                "('李四', '123456'), " +
                "('王五', '123456');");

        // 插入商品数据
        db.execSQL("INSERT INTO products (user_id, name, description, price, image_path) VALUES " +
                "(1, '全新笔记本电脑', '轻薄便携,性能出色，九成新', 3999.99, 'drawable/laptop'), " +
                "(2, '智能手表', '支持心率监测和运动追踪，几乎全新', 799.00, 'drawable/smartwatch'), " +
                "(3, '健身哑铃', '可调重量,适合初中高强度训练', 399.00, 'drawable/dumbbell'), " +
                "(1, '户外登山包', '容量大,材质耐用，容量大', 95.00, 'drawable/backpack'), " +
                "(2, '无线蓝牙音箱', '音质出众,续航时间长 适合初学者', 350.00, 'drawable/speaker');");


        // 插入交易数据
        db.execSQL("INSERT INTO transactions (buyer_id, seller_id, product_id, status, date) VALUES " +
                "(2, 1, 1, '已完成', '2024-12-08'), " +
                "(3, 2, 2, '已完成', '2024-12-09'), " +
                "(1, 3, 3, '待支付', '2024-12-03'), " +
                "(3, 1, 4, '已取消', '2024-12-04'), " +
                "(2, 3, 5, '已完成', '2024-12-05');");


        db.execSQL("INSERT INTO reviews (transaction_id, rating, comment) VALUES " +
                "(1, 5, '很好的卖家，商品质量不错,卖家很专业,物品成色很好'), " +
                "(2, 4, '交易顺利,收到商品很满意,推荐购买'), " +
                "(3, 3, '有点小问题,商品略有瑕疵,不过卖家态度很好'), " +
                "(4, 2, '物流很快,包装完好无损'), " +
                "(5, 5, '性价比很高,物有所值，推荐！');");





    }


    // 插入用户（注册）
    public boolean registerUser(String username, String password) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("username", username);
        values.put("password", password);

        long result = db.insert("users", null, values);
        db.close();
        return result != -1; // 返回插入是否成功
    }

    // 验证用户（登录）
    public boolean loginUser(String username, String password) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(
                "SELECT * FROM users WHERE username = ? AND password = ?",
                new String[]{username, password});
        boolean loginSuccess = cursor.getCount() > 0;
        cursor.close();
        db.close();
        return loginSuccess;
    }

    // 检查用户名是否存在
    public boolean isUsernameExists(String username) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(
                "SELECT * FROM users WHERE username = ?",
                new String[]{username});
        boolean exists = cursor.getCount() > 0;
        cursor.close();
        db.close();
        return exists;
    }





}
